using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinformDevelopFrame.IRepository;
using WinformDevelopFrame.Entity;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;

namespace WinformDevelopFrame.Repository
{
    public class sysroleRepository : BaseRepository<sysrole>, IsysroleRepository
    {
        private ISqlSugarClient _sqlSugarClient;
        public sysroleRepository(ISqlSugarClient sqlSugar) : base(sqlSugar)
        {
            _sqlSugarClient= sqlSugar;
        }

        public int Add(RoleM m)
        {
            int result = 0;
            try
            {
                _sqlSugarClient.Ado.BeginTran();
                result=Insert(m.Role);
                _sqlSugarClient.Insertable<sysrolemenu>(m.MenuList).ExecuteCommand();
                _sqlSugarClient.Ado.CommitTran();
            }
            catch (Exception e)
            {
                _sqlSugarClient.Ado.RollbackTran();
                throw;
            }
            return result;
        }

        public int AddList(List<sysrole> list)
        {
            return Insert(list);
        }

        public bool UpdateN(RoleM m)
        {
            try
            {
                _sqlSugarClient.Ado.BeginTran();
                Update(m.Role);
                _sqlSugarClient.Deleteable<sysrolemenu>(p => p.RoleId == m.Role.Id).ExecuteCommand();
                _sqlSugarClient.Insertable<sysrolemenu>(m.MenuList).ExecuteCommand();
                _sqlSugarClient.Ado.CommitTran();
            }
            catch (Exception e)
            {
                _sqlSugarClient.Ado.RollbackTran();
                throw;
            }
            return true;
        }

        public bool UpdateList(List<sysrole> list)
        {
            return Update(list);
        }

        public bool DeleteN(RoleM m)
        {
            try
            {
                _sqlSugarClient.Ado.BeginTran();
                Delete(m.Role);
                _sqlSugarClient.Deleteable<sysrolemenu>(p => p.RoleId == m.Role.Id).ExecuteCommand();
                _sqlSugarClient.Ado.CommitTran();
            }
            catch (Exception e)
            {
                _sqlSugarClient.Ado.RollbackTran();
                throw;
            }
            return true;
        }

        public bool DeleteList(List<sysrole> list)
        {
            return Delete(list);
        }

        public sysrole QueryById(int id)
        {
            return QueryByIdAsync(id).Result;
        }

        public List<sysrole> QueryList(List<int> ids)
        {
            return QueryByIDs(ids.ToArray());
        }
    }
}